<?php
namespace app\admin\controller\plat\weixin\wechat\material;

use app\admin\controller\Controller;
use app\admin\model\Material as MaterialModel;
use think\facade\View;

/**
 * 视频素材
 */
class Video extends Controller
{
    /**
     * 列表
     */
    public function index()
    {
        $model = new MaterialModel;
        $list = $model->getList(30);
        return View::fetch('index', compact('list'));
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $model = new MaterialModel;
            // 新增记录
            $file = request()->file('file');
            // 文件扩展名
            $fileExt = strtolower($file->extension());
            if($fileExt != 'mp4'){
                return $this->renderError('上传文件类型只能为mp4');
            }
            // 文件大小(字节)不能大于10M（1024*1024*10）
            $fileSize = $file->getSize(); 
            if($fileSize > 10485760){
                return $this->renderError('上传文件大于10M');
            }
            $fileInfo = pathinfo($file);
            $folder = date('Ymd');//日期文件夹
            $savePath = web_path() . 'uploads/admin/'.$folder;
            $info = $file->move($savePath);
            $file_name = $file->hashName(function () {
                return md5(uniqid((string)mt_rand(), true));
            });
            rename($savePath . DIRECTORY_SEPARATOR . $fileInfo['basename'],$savePath . DIRECTORY_SEPARATOR . $file_name);
            $file_path = 'admin/'.$folder.'/'.$file_name;
            // 新增记录
    		if($model->add($this->postData('data'),$file_path)){
    			return $this->renderSuccess('添加成功', url('plat.weixin.wechat.material.video/index'));
    		}
            $error = $model->getError() ?: '添加失败';
            return $this->renderError($error);
        }
        return redirect(url('plat.weixin.wechat.material.video/index')); 
    }
    /**
     * 编辑
     */
    public function edit(int $id)
    {
        $model = MaterialModel::get($id);
        if ($this->request->isGet()) {
            if($model){
               return $this->renderSuccess('', '', compact('model')); 
            }
            return $this->renderError('获取失败');
        }
        // 更新记录
        if ($model->edit($this->postData('data'))) {
            return $this->renderSuccess('更新成功', url('plat.weixin.wechat.material.video/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }
    /**
     * 删除
     */
    public function delete()
    {
        $data = $this->postData();
        $model = MaterialModel::get($data['id']);
        if (!$model->remove()) {
            $error = $model->getError() ?: '删除失败';
            return $this->renderError($error);
        }
        return $this->renderSuccess('删除成功');
    }
}